package org.bite.lesson12;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Demo1202 {
    public static void main(String[] args) throws InterruptedException {
        // 指定参赛选手的个数(线程数)
        CountDownLatch countDownLatch = new CountDownLatch(10);

        System.out.println("各就各位,预备...");
        for (int i = 0; i < 10; i++) {
            Thread player = new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "开跑.");
                    // 模拟比赛过程, 休眠2秒
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "到达.");
                    // 标记选手已达到终点,让countDownLatch的计数减1, 当计数到0时,表示所有的选手都到达终点,比赛结束
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "player" + i);
            // 启动线程
            player.start();
        }

        TimeUnit.MILLISECONDS.sleep(10);
        System.out.println("===== 比赛进行中 =====");
        // 等待比赛结束
        countDownLatch.await();
        // 颁奖
        System.out.println("比赛结束, 进行颁奖");
    }
}
